package com.laundry.user.ui.main

import android.Manifest
import android.content.pm.PackageManager
import android.location.Location
import android.os.Bundle
import android.view.View
import androidx.activity.result.contract.ActivityResultContracts
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import com.google.android.gms.location.FusedLocationProviderClient
import com.google.android.gms.location.LocationServices
import com.google.android.material.bottomnavigation.BottomNavigationView
import com.laundry.user.R
import com.laundry.user.databinding.ActivityMainBinding
import com.laundry.user.ui.favorite.FavoriteFragment
import com.laundry.user.ui.home.HomeFragment
import com.laundry.user.ui.order.OrderFragment
import com.laundry.user.ui.profile.ProfileFragment
import com.laundry.user.utils.LocationUtils
import com.laundry.user.utils.PermissionUtils
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch

@AndroidEntryPoint
class MainActivity : AppCompatActivity() {
    
    private lateinit var binding: ActivityMainBinding
    private val viewModel: MainViewModel by viewModels()
    
    private lateinit var fusedLocationClient: FusedLocationProviderClient
    private var currentLocation: Location? = null
    
    // 权限请求启动器
    private val locationPermissionLauncher = registerForActivityResult(
        ActivityResultContracts.RequestMultiplePermissions()
    ) { permissions ->
        val fineLocationGranted = permissions[Manifest.permission.ACCESS_FINE_LOCATION] ?: false
        val coarseLocationGranted = permissions[Manifest.permission.ACCESS_COARSE_LOCATION] ?: false
        
        if (fineLocationGranted || coarseLocationGranted) {
            getCurrentLocation()
        } else {
            // 权限被拒绝，使用默认位置或提示用户
            viewModel.setLocationPermissionDenied()
        }
    }
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)
        
        initViews()
        initLocation()
        observeViewModel()
        
        // 默认显示首页
        if (savedInstanceState == null) {
            showFragment(HomeFragment(), "home")
        }
    }
    
    private fun initViews() {
        setupBottomNavigation()
        setupToolbar()
    }
    
    private fun setupBottomNavigation() {
        binding.bottomNavigation.setOnItemSelectedListener { item ->
            when (item.itemId) {
                R.id.nav_home -> {
                    showFragment(HomeFragment(), "home")
                    true
                }
                R.id.nav_order -> {
                    showFragment(OrderFragment(), "order")
                    true
                }
                R.id.nav_favorite -> {
                    showFragment(FavoriteFragment(), "favorite")
                    true
                }
                R.id.nav_profile -> {
                    showFragment(ProfileFragment(), "profile")
                    true
                }
                else -> false
            }
        }
    }
    
    private fun setupToolbar() {
        setSupportActionBar(binding.toolbar)
        supportActionBar?.setDisplayShowTitleEnabled(false)
    }
    
    private fun initLocation() {
        fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
        requestLocationPermission()
    }
    
    private fun requestLocationPermission() {
        when {
            PermissionUtils.hasLocationPermission(this) -> {
                getCurrentLocation()
            }
            shouldShowRequestPermissionRationale(Manifest.permission.ACCESS_FINE_LOCATION) -> {
                // 显示权限说明对话框
                PermissionUtils.showLocationPermissionDialog(this) {
                    locationPermissionLauncher.launch(
                        arrayOf(
                            Manifest.permission.ACCESS_FINE_LOCATION,
                            Manifest.permission.ACCESS_COARSE_LOCATION
                        )
                    )
                }
            }
            else -> {
                locationPermissionLauncher.launch(
                    arrayOf(
                        Manifest.permission.ACCESS_FINE_LOCATION,
                        Manifest.permission.ACCESS_COARSE_LOCATION
                    )
                )
            }
        }
    }
    
    private fun getCurrentLocation() {
        if (!PermissionUtils.hasLocationPermission(this)) {
            return
        }
        
        try {
            fusedLocationClient.lastLocation.addOnSuccessListener { location ->
                if (location != null) {
                    currentLocation = location
                    viewModel.updateLocation(location.latitude, location.longitude)
                } else {
                    // 获取不到位置，请求新的位置
                    LocationUtils.requestNewLocation(fusedLocationClient) { newLocation ->
                        currentLocation = newLocation
                        viewModel.updateLocation(newLocation.latitude, newLocation.longitude)
                    }
                }
            }.addOnFailureListener { exception ->
                // 位置获取失败
                viewModel.setLocationError(exception.message ?: "位置获取失败")
            }
        } catch (e: SecurityException) {
            // 权限异常
            viewModel.setLocationPermissionDenied()
        }
    }
    
    private fun observeViewModel() {
        lifecycleScope.launch {
            viewModel.uiState.collect { state ->
                updateUI(state)
            }
        }
        
        lifecycleScope.launch {
            viewModel.events.collect { event ->
                handleEvent(event)
            }
        }
    }
    
    private fun updateUI(state: MainUiState) {
        // 更新加载状态
        binding.progressBar.visibility = if (state.isLoading) View.VISIBLE else View.GONE
        
        // 更新网络状态
        if (!state.isNetworkAvailable) {
            showNetworkError()
        } else {
            hideNetworkError()
        }
        
        // 更新位置信息
        state.currentLocation?.let { location ->
            updateLocationDisplay(location)
        }
        
        // 更新用户信息
        state.userProfile?.let { profile ->
            updateUserProfile(profile)
        }
    }
    
    private fun handleEvent(event: MainEvent) {
        when (event) {
            is MainEvent.ShowError -> {
                showError(event.message)
            }
            is MainEvent.ShowLocationPermissionDialog -> {
                PermissionUtils.showLocationPermissionDialog(this) {
                    requestLocationPermission()
                }
            }
            is MainEvent.NavigateToLogin -> {
                navigateToLogin()
            }
            is MainEvent.ShowLocationSettings -> {
                LocationUtils.showLocationSettingsDialog(this)
            }
        }
    }
    
    private fun showFragment(fragment: Fragment, tag: String) {
        val currentFragment = supportFragmentManager.findFragmentById(R.id.fragment_container)
        
        if (currentFragment?.tag == tag) {
            return
        }
        
        supportFragmentManager.beginTransaction()
            .replace(R.id.fragment_container, fragment, tag)
            .commit()
    }
    
    private fun updateLocationDisplay(location: com.laundry.user.data.model.Location) {
        binding.locationText.text = location.address ?: "定位中..."
        binding.locationText.visibility = View.VISIBLE
    }
    
    private fun updateUserProfile(profile: com.laundry.user.data.model.UserProfile) {
        // 更新用户头像和信息
        binding.userAvatar.visibility = View.VISIBLE
        // 加载用户头像等
    }
    
    private fun showNetworkError() {
        binding.networkErrorView.visibility = View.VISIBLE
        binding.networkErrorView.setOnClickListener {
            viewModel.retry()
        }
    }
    
    private fun hideNetworkError() {
        binding.networkErrorView.visibility = View.GONE
    }
    
    private fun showError(message: String) {
        // 显示错误提示
        com.google.android.material.snackbar.Snackbar.make(
            binding.root,
            message,
            com.google.android.material.snackbar.Snackbar.LENGTH_LONG
        ).show()
    }
    
    private fun navigateToLogin() {
        // 跳转到登录页面
        val intent = android.content.Intent(this, com.laundry.user.ui.auth.LoginActivity::class.java)
        startActivity(intent)
        finish()
    }
    
    override fun onResume() {
        super.onResume()
        // 检查网络状态
        viewModel.checkNetworkStatus()
        
        // 刷新用户信息
        if (viewModel.isLoggedIn()) {
            viewModel.refreshUserProfile()
        }
    }
    
    override fun onDestroy() {
        super.onDestroy()
        viewModel.cleanup()
    }
    
    // 提供给Fragment使用的方法
    fun getCurrentLocation(): Location? = currentLocation
    
    fun requestLocationUpdate() {
        getCurrentLocation()
    }
    
    fun showBottomNavigation() {
        binding.bottomNavigation.visibility = View.VISIBLE
    }
    
    fun hideBottomNavigation() {
        binding.bottomNavigation.visibility = View.GONE
    }
    
    fun setToolbarTitle(title: String) {
        binding.toolbarTitle.text = title
    }
    
    fun showToolbar() {
        binding.toolbar.visibility = View.VISIBLE
    }
    
    fun hideToolbar() {
        binding.toolbar.visibility = View.GONE
    }
}

// UI状态数据类
data class MainUiState(
    val isLoading: Boolean = false,
    val isNetworkAvailable: Boolean = true,
    val currentLocation: com.laundry.user.data.model.Location? = null,
    val userProfile: com.laundry.user.data.model.UserProfile? = null,
    val hasLocationPermission: Boolean = false,
    val error: String? = null
)

// 事件数据类
sealed class MainEvent {
    data class ShowError(val message: String) : MainEvent()
    object ShowLocationPermissionDialog : MainEvent()
    object NavigateToLogin : MainEvent()
    object ShowLocationSettings : MainEvent()
}
